import { useQuery } from 'react-query';
import { TBill } from '@/types';
import { request } from '@/request';
import { useParams, useHistory } from 'react-router-dom';
import { IconBox, CircleContainer, Modal } from '@/components';
import { toLocalTime, getIcon } from '@/utils';
import {
   EditIcon,
   PaymentIcon,
   DateIcon,
   LocationIcon,
   DeleteIcon,
} from '@/components/icons';
import DetailBtnContainer from '@/components/Layout/DetailBtnContainer';
import useGlobalVar from '@/hooks/useGlobalVar';
import { PieChart, Pie, ResponsiveContainer, Cell } from 'recharts';

const BillDetail = () => {
   let { id } = useParams();
   const history = useHistory();
   const { user } = useGlobalVar();

   const { data } = useQuery('bill', async () =>
      request(`/bill`, {
         params: {
            id,
         },
      })
   );

   const goEdit = () => {
      history.push(`/bill/${id}`);
   };

   const handleDelete = () => {
      Modal.confirm({
         content: '确认要删除吗？',
         onOk: () => {
            request('/bills/delete', {
               method: 'DELETE',
               data: {
                  ids: [id],
               },
               showSuccess: true,
               success: () => {
                  window.history.back();
               },
            });
         },
      });
   };

   if (!data) return <div>Loding...</div>;
   const bill = data.data;

   const renderCustomizedLabel = (props) => {
      const { x, y, value, name } = props;
      const isSeft = user.username === name;
      return (
         <text
            x={x}
            y={y}
            dy={8}
            textAnchor="middle"
            fill={isSeft ? '#151436' : '#a2a2a2'}
         >
            {isSeft ? '我' : name}: {value}
         </text>
      );
   };
   const chartData = bill.details.map((item) => ({
      name: item.username,
      value: item.account,
   }));

   return (
      <>
         <div className="flex gap-1">
            <IconBox background={bill.category.color}>
               {getIcon(bill.category.icon, {
                  type: 'white',
               })}
            </IconBox>
            <span className="color-disabled">
               {bill.bill_desc || bill.category.category_name}
            </span>
         </div>
         <div className="flex justify-end items-end">
            <span className="color-main">-{bill.account}</span>
            <span className="color-disabled text-base">￥</span>
         </div>
         <div className="my-2 border-t h-0 border-dashed"></div>
         <div className="flex flex-col items-center gap-1 my-2 text-sm color-disabled">
            <div className="w-full flex-base">
               <span className="flex">
                  <DateIcon size={18} />
                  <span className="ml-1">日期</span>
               </span>
               <span>{toLocalTime(bill.updatedAt)}</span>
            </div>
            <div className="w-full flex-base">
               <span className="flex">
                  <PaymentIcon size={18} />
                  <span className="ml-1">付款人</span>
               </span>
               <span>{bill.createdBy.username}</span>
            </div>

            <div className="w-full flex-base">
               <span className="flex">
                  <LocationIcon size={18} />
                  <span className="ml-1">位置</span>
               </span>
               <span>位置</span>
            </div>
         </div>
         <div className="my-2 border-t h-0 border-dashed"></div>
         <div className="w-full h-36 mt-4 font-roboto">
            <ResponsiveContainer width="100%" height="100%">
               <PieChart
                  width={400}
                  height={400}
                  margin={{
                     top: 100,
                  }}
               >
                  <Pie
                     dataKey="value"
                     startAngle={180}
                     endAngle={0}
                     data={chartData}
                     cx="50%"
                     cy="50%"
                     outerRadius={80}
                     label={renderCustomizedLabel}
                  >
                     {chartData.map((entry, index) => {
                        return (
                           <Cell
                              key={`cell-${index}`}
                              fill={
                                 user.username === entry.name
                                    ? '#8884d8'
                                    : '#b7b4ee'
                              }
                           />
                        );
                     })}
                  </Pie>
               </PieChart>
            </ResponsiveContainer>
         </div>

         <DetailBtnContainer>
            {bill.createdBy._id === user._id && (
               <>
                  <CircleContainer onClick={goEdit}>
                     <EditIcon type="primary" />
                  </CircleContainer>
                  <CircleContainer onClick={handleDelete}>
                     <DeleteIcon type="danger" />
                  </CircleContainer>
               </>
            )}
         </DetailBtnContainer>
      </>
   );
};
export default BillDetail;
